package com.karolak.sm;

import java.util.ArrayList;
import java.util.List;

import com.karolak.sm.event.CbConstants.CbEvent;
import com.karolak.sm.event.CbConstants.CbStateId;
import com.karolak.sm.state.CbState;
import com.karolak.sm.state.State;
import com.karolak.sm.state.StateBaseCb;
import com.karolak.sm.state.Transition;

public class CbMachineImpl extends StateMachineImpl implements CbMachine {

	public CbMachineImpl() {
		List<State> states = new ArrayList<State>();
		List<Transition> transitions = new ArrayList<Transition>();

		states.add(new StateBaseCb(this, CbStateId.DISCONNECTED));
		states.add(new StateBaseCb(this, CbStateId.CONNECTED));

		transitions.add(new Transition(CbEvent.CONNECT, CbStateId.DISCONNECTED, CbStateId.CONNECTED));
		transitions.add(new Transition(CbEvent.DISCONNECT, CbStateId.CONNECTED, CbStateId.DISCONNECTED));

		registerStates(states);
		registerTransitions(transitions);

		setState(getConfig().getState(CbStateId.DISCONNECTED));
	}

	// === transition api === //
	public void connect() {
		try {
			getState().connect();
		} catch (Exception e) {
			handleException(e);
		}
	}

	public void disconnect() {
		try {
			getState().disconnect();
		} catch (Exception e) {
			handleException(e);
		}
	}

	// === get/set === //
	public CbState getState() {
		return (CbState) super.getState();
	}
}
